// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <cantor/catalog/table_querier.h>

namespace cantor::catalog {

      turbo::Result<int64_t> TableQuerier::table_id(const std::string &name) const {
        std::shared_lock lk(_table_manager->_mutex);
        auto it = _table_manager->_table_id_map.find(name);
        if (it == _table_manager->_table_id_map.end()) {
            return turbo::not_found_error("not found database:", name);
        }
        return it->second;
    }

    turbo::Result<std::shared_ptr<TableInfo> > TableQuerier::table_info(const std::string &name) const {
        std::shared_lock lk(_table_manager->_mutex);
        auto it = _table_manager->_table_id_map.find(name);
        if (it == _table_manager->_table_id_map.end()) {
            return turbo::not_found_error("not found database:", name);
        }

        auto info_it = _table_manager->_table_map.find(it->second);
        if (info_it == _table_manager->_table_map.end()) {
            return turbo::internal_error("found database:", name, "id:", it->second, "but no info");
        }
        return info_it->second;
    }

    turbo::Result<std::shared_ptr<TableInfo> > TableQuerier::table_info(int64_t ns_id) const {
        std::shared_lock lk(_table_manager->_mutex);

        auto info_it = _table_manager->_table_map.find(ns_id);
        if (info_it == _table_manager->_table_map.end()) {
            return turbo::not_found_error("found database with id:", ns_id);
        }
        return info_it->second;
    }

}  // namespace cantor::catalog
